package cn.edu.baiyunu.myapplication

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import cn.edu.baiyunu.myapplication.data.db.AppDatabase
import cn.edu.baiyunu.myapplication.data.db.entity.PhotoRecord
import cn.edu.baiyunu.myapplication.data.db.entity.UserPreference
import cn.edu.baiyunu.myapplication.data.model.PhotoSpec
import cn.edu.baiyunu.myapplication.data.repository.PhotoRepositoryImpl
import cn.edu.baiyunu.myapplication.data.repository.PreferenceRepository
import cn.edu.baiyunu.myapplication.data.repository.PreferenceRepositoryImpl
import cn.edu.baiyunu.myapplication.ui.components.BottomNavigationBar
import cn.edu.baiyunu.myapplication.ui.create.CreateScreen
import cn.edu.baiyunu.myapplication.ui.create.CreateSuccessScreen
import cn.edu.baiyunu.myapplication.ui.edit.EditScreen
import cn.edu.baiyunu.myapplication.ui.edit.EditViewModel
import cn.edu.baiyunu.myapplication.ui.history.HistoryScreen
import cn.edu.baiyunu.myapplication.ui.history.HistoryViewModel
import cn.edu.baiyunu.myapplication.ui.history.HistoryViewModelFactory
import cn.edu.baiyunu.myapplication.ui.home.HomeScreen
import cn.edu.baiyunu.myapplication.ui.home.HomeViewModel
import cn.edu.baiyunu.myapplication.ui.home.HomeViewModelFactory
import cn.edu.baiyunu.myapplication.ui.specs.SpecsScreen
import cn.edu.baiyunu.myapplication.ui.specs.SpecsViewModel
import cn.edu.baiyunu.myapplication.ui.specs.SpecsViewModelFactory
import cn.edu.baiyunu.myapplication.ui.theme.MyApplicationTheme
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import java.io.File

class MainActivity : ComponentActivity() {
    // 主视图模型
    private lateinit var homeViewModel: HomeViewModel
    private lateinit var historyViewModel: HistoryViewModel
    private lateinit var specsViewModel: SpecsViewModel
    private lateinit var editViewModel: EditViewModel
    
    // 数据仓库
    private lateinit var photoRepository: PhotoRepositoryImpl
    private lateinit var preferenceRepository: PreferenceRepository
    
    // 存储权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.entries.all { it.value }
        if (allGranted) {
            Log.d("MainActivity", "所有请求的权限已获取")
        } else {
            // 未获取全部权限，提示用户
            Toast.makeText(this, "保存图片需要存储权限", Toast.LENGTH_LONG).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 检查和请求权限
        requestRequiredPermissions()
        
        // 初始化数据仓库
        val database = AppDatabase.getDatabase(applicationContext)
        photoRepository = PhotoRepositoryImpl(database.photoRecordDao())
        preferenceRepository = PreferenceRepositoryImpl(database.userPreferenceDao())
        
        // 创建HomeViewModel
        val homeViewModelFactory = HomeViewModelFactory(preferenceRepository, photoRepository)
        homeViewModel = ViewModelProvider(this, homeViewModelFactory)[HomeViewModel::class.java]
        
        // 创建HistoryViewModel
        val historyViewModelFactory = HistoryViewModelFactory(photoRepository)
        historyViewModel = ViewModelProvider(this, historyViewModelFactory)[HistoryViewModel::class.java]
        
        // 创建SpecsViewModel
        val specsViewModelFactory = SpecsViewModelFactory(preferenceRepository)
        specsViewModel = ViewModelProvider(this, specsViewModelFactory)[SpecsViewModel::class.java]
        
        // 创建EditViewModel
        val editViewModelFactory = EditViewModel.Factory(this, photoRepository)
        editViewModel = ViewModelProvider(this, editViewModelFactory)[EditViewModel::class.java]
        
        setContent {
            MyApplicationTheme {
                // 应用主界面
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color.White
                ) {
                    AppNavHost()
                }
            }
        }
    }
    
    /**
     * 检查和请求必要的权限
     */
    private fun requestRequiredPermissions() {
        // 存储权限 - 根据Android版本选择合适的权限
        val storagePermissions = when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                // Android 13 及以上使用READ_MEDIA_IMAGES
                arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                // Android 10-12使用READ_EXTERNAL_STORAGE
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            else -> {
                // Android 9及以下需要读写权限
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            }
        }
        
        // 相机权限
        val cameraPermission = Manifest.permission.CAMERA
        
        // 所有需要的权限
        val requiredPermissions = storagePermissions + cameraPermission
        
        // 检查哪些权限需要请求
        val permissionsToRequest = requiredPermissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }.toTypedArray()
        
        // 如果有需要请求的权限，发起请求
        if (permissionsToRequest.isNotEmpty()) {
            Log.d("MainActivity", "正在请求以下权限: ${permissionsToRequest.joinToString()}")
            requestPermissionLauncher.launch(permissionsToRequest)
        } else {
            Log.d("MainActivity", "所有必要权限已获取")
        }
    }
    
    /**
     * 打开系统相册DCIM目录
     */
    fun openSavedImagesFolder() {
        try {
            // 尝试多种方式打开相册DCIM目录
            
            // 方式1：直接打开系统相册
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(Uri.parse("content://media/external/images/media"), "image/*")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
                return
            }
            
            // 方式2：使用ACTION_GET_CONTENT打开图片选择器
            val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
            galleryIntent.type = "image/*"
            galleryIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            
            if (galleryIntent.resolveActivity(packageManager) != null) {
                startActivity(galleryIntent)
                return
            }
            
            // 方式3：尝试打开特定厂商的相册应用
            val packageNames = arrayOf(
                "com.android.gallery3d", // 原生
                "com.sec.android.gallery3d", // 三星
                "com.miui.gallery", // 小米
                "com.huawei.gallery" // 华为
            )
            
            for (packageName in packageNames) {
                try {
                    val appIntent = packageManager.getLaunchIntentForPackage(packageName)
                    if (appIntent != null) {
                        appIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(appIntent)
                        return
                    }
                } catch (e: Exception) {
                    // 忽略特定包找不到的异常
                }
            }
            
            // 最后显示提示
            Toast.makeText(this, "请查看手机相册的DCIM目录，那里有您保存的照片", Toast.LENGTH_LONG).show()
            
        } catch (e: Exception) {
            Log.e("MainActivity", "打开相册失败: ${e.message}")
            Toast.makeText(this, "无法打开相册，请手动打开手机相册查看DCIM目录中的照片", Toast.LENGTH_LONG).show()
        }
    }
    
    /**
     * 应用主界面导航
     */
    @Composable
    fun AppNavHost() {
        val navController = rememberNavController()
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentRoute = navBackStackEntry?.destination?.route ?: "home"
        
        // 是否显示底部导航栏
        var showBottomNav by remember { mutableStateOf(true) }
        
        // 检查是否应该显示底部导航栏
        LaunchedEffect(currentRoute) {
            showBottomNav = when (currentRoute) {
                "edit", "edit/{photoId}" -> false
                else -> true
            }
        }
        
        Scaffold(
            bottomBar = {
                if (showBottomNav) {
                    BottomNavigationBar(
                        currentRoute = currentRoute,
                        onNavigateToRoute = { route -> navController.navigate(route) }
                    )
                }
            }
        ) { paddingValues ->
            NavHost(
                navController = navController,
                startDestination = "home",
                modifier = Modifier.padding(paddingValues)
            ) {
                // 首页
                composable("home") {
                    HomeScreen(
                        viewModel = homeViewModel,
                        onNavigateToUpload = { 
                            navController.navigate("create")
                        },
                        onNavigateToSpecs = {
                            navController.navigate("specs")
                        },
                        onNavigateToHistory = {
                            navController.navigate("history")
                        },
                        onPhotoClick = { photo: PhotoRecord -> 
                            navController.navigate("edit/${photo.id}")
                        },
                        onSpecClick = { spec: PhotoSpec ->
                            // 传递规格参数到创作页面
                            navController.navigate("create?specType=${spec.name}")
                        },
                        onNotificationClick = {
                            // 通知功能
                        },
                        onSettingsClick = {
                            // 设置功能
                        }
                    )
                }
                
                // 创建页面
                composable("create") {
                    CreateScreen(
                        onNavigateUp = { navController.navigateUp() },
                        navigateToSuccess = { navController.navigate("create_success") },
                        navigateToEdit = { photoUri ->
                            navController.navigate("edit?photoUri=${Uri.encode(photoUri.toString())}")
                        }
                    )
                }
                
                // 创建成功页面
                composable("create_success") {
                    CreateSuccessScreen(
                        onNavigateUp = { navController.navigateUp() },
                        onNavigateToHome = { navController.navigate("home") },
                        onNavigateToHistory = { navController.navigate("history") }
                    )
                }
                
                // 历史页面
                composable("history") {
                    HistoryScreen(
                        viewModel = historyViewModel,
                        onNavigateToUpload = { navController.navigate("create") },
                        onNavigateToEdit = { photoRecord ->
                            navController.navigate("edit/${photoRecord.id}")
                        },
                        onNavigateToHome = { navController.navigate("home") },
                        onNavigateToSpecs = { navController.navigate("specs") },
                        onOpenSavedFolder = { openSavedImagesFolder() }
                    )
                }
                
                // 规格页面
                composable("specs") {
                    SpecsScreen(
                        viewModel = specsViewModel,
                        onNavigateBack = { navController.navigateUp() },
                        onNavigateToHome = { navController.navigate("home") },
                        onNavigateToCreate = { navController.navigate("create") },
                        onNavigateToHistory = { navController.navigate("history") },
                        onSpecSelected = { spec ->
                            // 选择规格后导航到编辑页面，并传递规格ID
                            navController.navigate("edit?specId=${spec.id}")
                        }
                    )
                }
                
                // 编辑页面
                composable(
                    route = "edit?photoUri={photoUri}&specId={specId}",
                    arguments = listOf(
                        navArgument("photoUri") {
                            type = NavType.StringType
                            nullable = true
                            defaultValue = null
                        },
                        navArgument("specId") {
                            type = NavType.StringType
                            nullable = true
                            defaultValue = null
                        }
                    )
                ) { backStackEntry ->
                    val photoUriString = backStackEntry.arguments?.getString("photoUri")
                    val photoUri = if (photoUriString != null) Uri.parse(photoUriString) else null
                    val specId = backStackEntry.arguments?.getString("specId")
                    
                    LaunchedEffect(photoUri, specId) {
                        if (photoUri != null) {
                            editViewModel.loadImage(photoUri)
                        }
                        if (specId != null) {
                            editViewModel.selectSpecById(specId)
                        }
                    }
                    
                    EditScreen(
                        viewModel = editViewModel,
                        onNavigateBack = { navController.navigateUp() },
                        onNavigateToResult = {
                            // 导航到结果页面
                            navController.navigate("create_success")
                        }
                    )
                }
                
                // 从ID加载照片编辑页面
                composable(
                    route = "edit/{photoId}",
                    arguments = listOf(
                        navArgument("photoId") {
                            type = NavType.LongType
                        }
                    )
                ) { backStackEntry ->
                    val photoId = backStackEntry.arguments?.getLong("photoId") ?: 0
                    
                    LaunchedEffect(photoId) {
                        if (photoId > 0) {
                            editViewModel.loadImageFromId(photoId)
                        }
                    }
                    
                    EditScreen(
                        viewModel = editViewModel,
                        onNavigateBack = { navController.navigateUp() },
                        onNavigateToResult = {
                            navController.navigate("create_success")
                        }
                    )
                }
            }
        }
    }
}
